"""
物品管理模块 - 负责物品的发布、浏览和搜索功能
作者：
- B同学：物品发布交互
- C同学：浏览/搜索交互和显示格式化
- D同学：物品筛选和搜索算法
"""

import datetime

# B同学负责的函数
def get_item_details_for_posting():
    """获取物品发布详情"""
    print("\n\033[1;33m===== 发布闲置物品 📢 =====")
    name = input("请输入物品名称: ").strip()
    if not name:
        print("\033[1;31m物品名称不能为空！ ❌")
        return None

    description = input("请输入物品描述: ").strip()

    # 处理价格输入
    while True:
        price_input = input("请输入期望价格（若免费/交换，请输入'免费'或'交换'）: ").strip()
        if price_input.lower() in ['免费', '交换']:
            price = price_input
            break
        try:
            price = float(price_input)
            if price < 0:
                print("\033[1;31m价格不能为负数！ ❌")
            else:
                break
        except ValueError:
            print("\033[1;31m请输入有效的价格！ ❌")

    # 处理联系方式
    while True:
        contact_info = input("请输入联系方式（如QQ号或手机号后四位）: ").strip()
        if not contact_info:
            print("\033[1;31m联系方式不能为空！ ❌")
        else:
            break

    # 处理分类选择
    print("\n可选分类:")
    categories = ["图书 📚", "日用 🧴", "电子产品 💻", "衣物 👚", "运动 🏋️", "其他 📦"]
    for i, category in enumerate(categories, 1):
        print(f"{i}. {category}")

    while True:
        try:
            category_choice = input("请选择物品分类（输入序号）: ").strip()
            if not category_choice:
                category = "其他 📦"
                break
            category_index = int(category_choice) - 1
            if 0 <= category_index < len(categories):
                category = categories[category_index]
                break
            else:
                print("\033[1;31m无效的分类序号！ ❌")
        except ValueError:
            print("\033[1;31m请输入有效的序号！ ❌")

    # 获取发布者标识
    publisher_id = input("请输入发布者标识（如学号或自定义口令）: ").strip()
    if not publisher_id:
        print("\033[1;31m发布者标识不能为空！ ❌")
        return None

    # 创建新物品
    return {
        'name': name,
        'description': description,
        'price': price,
        'contact_info': contact_info,
        'category': category,
        'publisher_id': publisher_id,
        'post_time': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        'status': 'available'
    }


# B同学负责的函数
def post_new_item_interaction():
    """发布新物品交互"""
    return get_item_details_for_posting()


# C同学负责的函数
def browse_or_search_items_interaction(all_items):
    """浏览/搜索物品交互"""
    print("\n\033[1;34m===== 浏览/搜索物品 🔍 =====")
    print("1. 📂 按分类浏览")
    print("2. ⏰ 按时间顺序浏览最新发布")
    print("3. 🔎 搜索物品")
    print("4. ↩️ 返回主菜单")

    while True:
        choice = input("\033[0m请选择操作（1-4）: ").strip()
        if choice == '1':
            # 按分类浏览
            print("\n可选分类:")
            categories = sorted(list({item['category'] for item in all_items if item['status'] == 'available'}))

            if not categories:
                print("\033[1;30m暂无物品分类！ 🌱")
                continue

            for i, category in enumerate(categories, 1):
                print(f"{i}. {category}")

            while True:
                try:
                    category_choice = input("请选择分类（输入序号）: ").strip()
                    if not category_choice:
                        break

                    category_index = int(category_choice) - 1
                    if 0 <= category_index < len(categories):
                        selected_category = categories[category_index]
                        category_items = filter_items_by_category(all_items, selected_category)
                        display_items(category_items)
                        break
                    else:
                        print("\033[1;31m无效的分类序号！ ❌")
                except ValueError:
                    print("\033[1;31m请输入有效的序号！ ❌")

        elif choice == '2':
            # 按时间顺序浏览最新发布
            while True:
                try:
                    n = input("请输入要浏览的最新物品数量（默认10）: ").strip()
                    if not n:
                        n = 10
                    else:
                        n = int(n)

                    recent_items = get_latest_items(all_items, n)
                    display_items(recent_items)
                    break
                except ValueError:
                    print("\033[1;31m请输入有效的数字！ ❌")

        elif choice == '3':
            # 搜索物品
            keyword = input("请输入搜索关键词: ").strip().lower()
            if not keyword:
                print("\033[1;31m搜索关键词不能为空！ ❌")
                continue

            search_results = search_items_by_keyword(all_items, keyword)
            display_items(search_results)

        elif choice == '4':
            # 返回主菜单
            return

        else:
            print("\033[1;31m无效的选择，请重新输入！ ❌")


# C同学负责的函数
def display_items(items_to_display):
    """显示物品列表"""
    # 过滤掉非在售物品
    filtered_items = [item for item in items_to_display if item['status'] == 'available']

    if not filtered_items:
        print("\033[1;30m暂无在售物品！ 🌱")
        return

    print("\n\033[1;36m物品列表:")
    print(f"{'ID':<10}{'名称':<15}{'价格':<10}{'分类':<8}{'发布时间':<20}")
    print("-" * 65)

    for item in filtered_items:
        print(format_item_for_display(item))


# C同学负责的函数
def format_item_for_display(item_dict, detail_level="summary"):
    """格式化物品显示"""
    price = format_price(item_dict['price'])

    if detail_level == "summary":
        return (
            f"{item_dict['item_id']:<10}"
            f"{item_dict['name'][:15]:<15}"
            f"{price:<10}"
            f"{item_dict['category'][:8]:<8}"
            f"{item_dict['post_time']:<20}"
        )
    else:  # full detail
        return (
            f"ID: {item_dict['item_id']}\n"
            f"名称: {item_dict['name']}\n"
            f"描述: {item_dict['description']}\n"
            f"价格: {price}\n"
            f"分类: {item_dict['category']}\n"
            f"联系方式: {item_dict['contact_info']}\n"
            f"发布时间: {item_dict['post_time']}\n"
            f"状态: {item_dict['status']}"
        )


def format_price(price):
    """格式化价格显示"""
    if isinstance(price, float):
        return f"¥{price:.2f}"
    return price


# D同学负责的函数
def filter_items_by_category(all_items, category):
    """按分类筛选物品"""
    return [item for item in all_items
            if item['category'] == category
            and item['status'] == 'available']


# D同学负责的函数
def get_latest_items(all_items, count=10):
    """获取最新物品"""
    available_items = [item for item in all_items if item['status'] == 'available']
    sorted_items = sorted(available_items,
                         key=lambda x: x['post_time'],
                         reverse=True)
    return sorted_items[:count]


# D同学负责的函数
def search_items_by_keyword(all_items, keyword):
    """关键词搜索物品"""
    return [item for item in all_items
            if (keyword in item['name'].lower() or
                keyword in item['description'].lower())
            and item['status'] == 'available']